package com.infra.server.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infra.server.config.SwaggerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.SwaggerResource;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author win
 * @date 2021/7/13 16:12
 * 资源类
 */
@RestController
public class ResourceController {

    @Resource
    private SwaggerConfig swaggerConfig;
    @Value("${server.port}")
    private String port;

    /**
     * 获取接口列表信息
     * @return
     */
    @GetMapping("/gateway/api/list")
    public JSONArray getApiList() {
        List<SwaggerResource> swaggerResourceList = swaggerConfig.get();
        JSONArray resourceList = new JSONArray();
        if (ObjectUtil.isNotEmpty(swaggerResourceList)) {
            for (SwaggerResource s : swaggerResourceList) {
                String url = s.getUrl();
                String contextPath = url.substring(0,url.indexOf(SwaggerConfig.API_URI));
                String result = HttpUtil.get("http://localhost:"+port+url);
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONObject paths = (JSONObject) jsonObject.get("paths");
                Set<String> pathsKeySet=paths.keySet();
                List<String> pathsKeyList= new ArrayList<>(pathsKeySet);
                JSONObject a,d;
                Set<String> b;
                List<String> c;
                for (String pathsKey : pathsKeyList) {
                    a = (JSONObject) paths.get(pathsKey);
                    b = a.keySet();
                    c = new ArrayList<>(b);
                    d = (JSONObject) a.get(c.get(0));
                    JSONObject object = new JSONObject();
                    object.put("name",contextPath+pathsKey);
                    object.put("description",d.get("summary"));
                    object.put("resourceType",d.get("description"));
                    object.put("httpMethod",c.get(0));
                    resourceList.add(object);
                }
            }
        }
        return resourceList;
    }
}
